/*
 * Copyright 2012 NJUT  qixiaobo. All rights reserved.
 */
package com.fujitsu.cn.fnst.view;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.context.Context;
import org.apache.velocity.tools.Scope;
import org.apache.velocity.tools.ToolManager;
import org.apache.velocity.tools.view.ViewToolContext;
import org.springframework.web.servlet.view.velocity.VelocityLayoutView;

/**
 * VelocityToolBox2View.java
 * 
 * @author Qixiaobo-win8
 */
public class VelocityToolBox2View extends VelocityLayoutView {
	private final String CLASS_PATH = "classpath:";
	@Override
	protected Context createVelocityContext(Map<String, Object> model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {// Create a
								// ChainedContext
								// instance.
		ViewToolContext ctx;

		ctx = new ViewToolContext(getVelocityEngine(), request, response,
				getServletContext());

		ctx.putAll(model);
		// 判断是否是在classpath
		if (this.getToolboxConfigLocation() != null) {
			ToolManager tm = new ToolManager();
			tm.setVelocityEngine(getVelocityEngine());
			if (!getToolboxConfigLocation().toLowerCase()
					.startsWith(CLASS_PATH)) {
				tm.configure(getServletContext().getRealPath(
						getToolboxConfigLocation()));
			} else {
				tm.configure(getClass()
						.getClassLoader()
						.getResource(
								getToolboxConfigLocation().substring(
										CLASS_PATH.length())).getPath());
			}
			if (tm.getToolboxFactory().hasTools(Scope.REQUEST)) {
				ctx.addToolbox(tm.getToolboxFactory().createToolbox(
						Scope.REQUEST));
			}
			if (tm.getToolboxFactory().hasTools(Scope.APPLICATION)) {
				ctx.addToolbox(tm.getToolboxFactory().createToolbox(
						Scope.APPLICATION));
			}
			if (tm.getToolboxFactory().hasTools(Scope.SESSION)) {
				ctx.addToolbox(tm.getToolboxFactory().createToolbox(
						Scope.SESSION));
			}
		}
		return ctx;
	}

}
